package cn.com.dhcc.turbo.web.controller.registry;

import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.util.HttpUtil;
import cn.com.dhcc.turbo.entity.registry.AdapterInfo;
import cn.com.dhcc.turbo.service.exch.ApiUserAuthService;
import cn.com.dhcc.turbo.service.registry.AdapterInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

/**
 * 适配器 controller
 * 
 * @日期：2014-10-20  
 * @作者：古玉龙
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/registry")
@TurboMenu(belongToMenu = LEAF_MENU.ADAPTER_BIND)
public class AdapterInfoController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.TURBO);
	@Autowired
	private AdapterInfoService adapterService;
	
	@Autowired
	private NodeInfoService nodeService;
	@Autowired
	ApiUserAuthService apiUserAuthService;
	
	@RequestMapping(value = "/adapter_info_list")
	public String list(Model model, Pager pager, String islocal, String nodeCode,String adapterName,String adapterType) {
		try {
			WhereCondition condition = new WhereCondition();
			if("".equals(islocal) || islocal ==null ){
				islocal = "1";
			}
			
			if (adapterType==null) {
				adapterType="0";
			}
			
			condition.where().eq("islocal", islocal);
			if (StringUtils.isNotBlank(nodeCode)) {
				condition.and();
				condition.eq("node_code", nodeCode);
			}
			if (StringUtils.isNotBlank(adapterName)) {
				condition.and();
				condition.like("ADAPTER_NAME", "%"+adapterName+"%");
			}
			
			if (StrUtil.isNotBlank(adapterType)) {
				condition.and().eq("adapter_type", adapterType);
			}

			
			condition.orderBy("WSDL_URL,mtime  desc");
			PagerData<AdapterInfo> pagerData = adapterService.getPagerList(pager, condition);
			List<AdapterInfo> nameList = adapterService.getLocalName();
			model.addAttribute("nameList", nameList);
			model.addAttribute("localNode", nodeService.getLocalNode());
			model.addAttribute(DATA_KEY, pagerData.getDatas());
			model.addAttribute("islocal", islocal);
			setTotoal(model, pagerData.getTotal());
		} catch (Exception e) {
			logger.error("获取适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_info_list";
		
	}
	
	@RequestMapping(value = "/adapter_info_exch")
	public String list(Model model,String adapterCode) {
		try {
			WhereCondition condition = new WhereCondition();
			condition.where().eq("islocal", "0").and().eq("ADAPTER_CODE", adapterCode).and().isNotNull("WSDL_URL");
			condition.orderBy("mtime  desc");
			List<AdapterInfo> adapter_list = adapterService.list(condition);
			model.addAttribute(DATA_KEY, adapter_list);
		} catch (Exception e) {
			logger.error("获取适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_info_exch";
		
	}
	
	 /* 适配器添加
	 * @param model
	 * @param nodeId
	 * @return
	 */
	@RequestMapping(value = "/adapter_info_add")
	public String adapterAdd(Model model, String nodeId) throws DaoException {
		try {
			AdapterInfo vo = new AdapterInfo();
			model.addAttribute(VO_KEY, vo);
		} catch (Exception e) {
			logger.error("添加适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_info_add";
	}

	

	@RequestMapping(value = "/adapter_info_update/{id}", method = RequestMethod.GET)
	public String adapterUpdate(@PathVariable String id, Model model) {
		try {
			AdapterInfo vo = adapterService.get(id);
			vo.setNoDeName(adapterService.getNoDeName(vo.getNodeCode()));
			model.addAttribute(DATA_KEY, vo);
		} catch (Exception e) {
			logger.error("添加适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_info_update";
	}

	/**
	 * 修改适配器
	 * @param model
	 * @param vo
	 * @param newNodeName
	 * @return
	 */
	@RequestMapping(value = "/update_adapter_info", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateAdapter(AdapterInfo vo, Model model) {

		try {
				vo.setMtime(new Date());
				String authCode=apiUserAuthService.createAuthCode(vo.getAdapterCode(), new URL(vo.getWsdlUrl()).getHost());//vo.getAdapterCode()+"_"+new URL(vo.getWsdlUrl()).getHost()+"_"+sdf.format(vo.getMtime());
				vo.setAuthCode(authCode);
				adapterService.updateAdapterAndSync(vo);
				
				return jsonSuccessResult("修改适配器成功");
		} catch (Exception e) {
			logger.error(" 修改适配器信息失败", e);
			return jsonFailResult("修改适配器信息失败");
		}
	}

	
	/**
	 * 根据Id解绑
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/adapter_info_unBind")
	@ResponseBody
	public Map<String, Object> unBindById(String id, Model model) {
		try {

			AdapterInfo vo = adapterService.get(id);
			vo.setWsdlUrl(null);
			vo.setAuthCode(null);
			adapterService.update(vo);
			adapterService.updateAdapterAndSync(vo);
			return jsonSuccessResult("适配器解绑成功");
		} catch (Exception e) {
			return jsonFailResult("适配器解绑失败");
		}
	}
	
	
	/**
	 * 根据Id禁用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/adapter_info_locked")
	@ResponseBody
	public Map<String, Object> lockedById(String id, Model model) {
		try {

			AdapterInfo vo = adapterService.get(id);

			vo.setMtime(new Date());
			vo.setStatus("1");
			adapterService.updateAdapterAndSync(vo);
			return jsonSuccessResult("适配器停止使用");
		} catch (Exception e) {
			return jsonFailResult("适配器禁用失败");
		}
	}

	/**
	 * 根据Id启用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/adapter_info_unlocked")
	@ResponseBody
	public Map<String, Object> unLockedById(String id, Model model) {
		try {
			AdapterInfo vo = adapterService.get(id);
			vo.setMtime(new Date());
			vo.setStatus("0");
			adapterService.updateAdapterAndSync(vo);
			return jsonSuccessResult("适配器启用成功");
		} catch (Exception e) {
			return jsonFailResult("适配器启用失败");
		}
	}

	/**
	 * 验证服务是否可以访问
	 * @param outBound
	 * @return
	 */
	@RequestMapping("/AdaisWsdlAvailable")
	@ResponseBody
	public Map<String, Object> isWsdlAvailable(@RequestParam("serviceUrl") String serviceUrl) {
		try {
			if (StringUtils.isNotBlank(serviceUrl)) {
				boolean ok = HttpUtil.checkUrl(serviceUrl);
				if (ok) {
					return jsonSuccessResult("校验地址");
				} else {
					return jsonFailResult("接口地址校验失败");
				}
			} else {
				return jsonFailResult("接口不能为空");
			}
		} catch (Exception e) {
			return jsonFailResult(e.getMessage());
		}

	}

	@RequestMapping(value = "/adapter_conf_sys/{id}", method = RequestMethod.GET)
	public String adapterConfSys(@PathVariable String id, Model model) {
		try {
			AdapterInfo vo = adapterService.get(id);
			vo.setNoDeName(adapterService.getNoDeName(vo.getNodeCode()));
			model.addAttribute(DATA_KEY, vo);
			
			//String sysIds = vo.getSysIds();
		   /* if(sysIds!=null){
		    	List<String> sysIdList = Arrays.asList(sysIds.split(","));
				model.addAttribute("sysIdList", JsonUtil.toJson(sysIdList));
		    }else{
		    	model.addAttribute("sysIdList", JsonUtil.toJson("NULL"));
		    }*/
		    
			
		} catch (Exception e) {
			logger.error("添加适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_conf_sys";
	}

	@RequestMapping(value = "/add_rel_adapter_sys", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addRelAdapterSys(Model model, String adapterId, String sysIds) {
		String msg = "";
		try {
			AdapterInfo vo = adapterService.get(adapterId);
			//vo.setSysIds(sysIds);
			vo.setMtime(new Date());
			adapterService.updateAdapterAndSync(vo);
			msg = "更新成功";
			return jsonSuccessResult(msg);
		} catch (Exception e) {
			msg = "更新或新增失败";
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
}
